package com.jiawa.wiki.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiawa.wiki.domain.Doc;
import com.jiawa.wiki.domain.DocExample;
import com.jiawa.wiki.mapper.DocMapper;
import com.jiawa.wiki.req.DocQueryReq;
import com.jiawa.wiki.req.DocSaveReq;
import com.jiawa.wiki.resp.DocQueryResp;
import com.jiawa.wiki.resp.PageResp;
import com.jiawa.wiki.util.CopyUtil;
import com.jiawa.wiki.util.SnowFlake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class DocService {


    @Resource
    private DocMapper docMapper;

    @Resource
    private SnowFlake snowFlake;

    private final static Logger LOG = LoggerFactory.getLogger(DocService.class);

    public PageResp<DocQueryResp> getlist(DocQueryReq req){

        DocExample docExample = new DocExample();
        DocExample.Criteria criteria = docExample.createCriteria();


        PageHelper.startPage(req.getPage(),req.getSize());

        //处理响应数据
        //存完整数据的列表
        List<Doc> doclist = docMapper.selectByExample(docExample);

        PageInfo<Doc> pageInfo = new PageInfo<>(doclist);

        LOG.info("总行数:{}",pageInfo.getTotal());
        LOG.info("总页数:{}",pageInfo.getPages());

        List<DocQueryResp> list = CopyUtil.copyList(doclist, DocQueryResp.class);

        PageResp<DocQueryResp> pageRsep = new PageResp<>();

        pageRsep.setTotal(pageInfo.getTotal());
        pageRsep.setList(list);

        return pageRsep;

    }

    public List<DocQueryResp> getall(){
        DocExample docExample = new DocExample();
        docExample.setOrderByClause("sort asc");
        List<Doc> doclist = docMapper.selectByExample(docExample);
        List<DocQueryResp> list = CopyUtil.copyList(doclist,DocQueryResp.class);
        return list;
    }

    public void save(DocSaveReq req){

        Doc doc = CopyUtil.copy(req,Doc.class);

        if (ObjectUtils.isEmpty(req.getId())) {
            //新增
            doc.setId(snowFlake.nextId());

            docMapper.insert(doc);
        }else {
            //更新
            docMapper.updateByPrimaryKey(doc);
        }
    }

    public void delete(long id){
        docMapper.deleteByPrimaryKey(id);

    }



}
